import json

from django.http import JsonResponse
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from django.db.models.deletion import ProtectedError
from role.models import Role


# Create your views here.
def role_page(request):
    # current_page  size 接收分页参数
    if request.method == 'POST':
        # {page:1,size:5}
        form_data = CustomerUtils.get_request_data(request)
        # 分页处理  total  tableData
        role_list = Role.objects.all().order_by('-id')
        # 获取分页对象
        paginator = Paginator(role_list, form_data.get('size', 5))
        # 获取数据总条数
        total = paginator.count
        # 当前页对象
        current_page = paginator.page(form_data.get('page', 1))
        # 当前页数据   [{},{},{}]
        table_data = list(current_page.object_list.values())
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'total': total,
            'tableData': table_data
        }
        return CustomerUtils.response_json(response)


def role_one(request, id):
    role = Role.objects.filter(id=id).first()
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'role': role
        }
    }
    return CustomerUtils.response_json(response)


def role_list(request):
    role_list = Role.objects.all()
    roles = []
    for role in role_list:
        roles.append({
            'id': role.id,
            'role_name': role.role_name
        })
    resp = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'roles': roles
        }
    }
    return CustomerUtils.response_json(resp)


def role_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        id = form_data.get('id')
        from django.db import IntegrityError
        try:
            if id is not None:
                # 更新
                Role.objects.filter(id=id).update(**form_data)
                response = {
                    'code': ResponseStatus.BUSINESS_SUCCESS,
                    'message': '更新成功'
                }
                return CustomerUtils.response_json(response)
            # 新增数据
            role = Role(**form_data)
            role.save()
            response = {
                'code': ResponseStatus.BUSINESS_SUCCESS,
                'message': '新增成功'
            }
            return CustomerUtils.response_json(response)
        except IntegrityError as e:
            response = {
                'code': ResponseStatus.BUSINESS_ERROR,
                'message': str(e)
            }
            return CustomerUtils.response_json(response)


def remove_one(request, id):
    # django.db.models.deletion.ProtectedError   role -> user   role_id    protect
    try:
        role = Role.objects.filter(id=id).delete()
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'message': '删除成功'
        }
        return CustomerUtils.response_json(response)
    except ProtectedError as e:
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message': '角色被占用,不能删除!!!'
        }
        return CustomerUtils.response_json(response)


def batch_remove(request):
    if request.method == 'POST':
        # {ids:[]}
        form_data = CustomerUtils.get_request_data(request)
        # 获取所有需要删除的角色id
        ids = form_data.get('ids')
        # delete from role where id in(1,2,3)
        try:
            Role.objects.filter(id__in=ids).delete()
            response = {
                'code': ResponseStatus.BUSINESS_SUCCESS,
                'message': '删除成功'
            }
            return CustomerUtils.response_json(response)
        except ProtectedError as e:
            response = {
                'code': ResponseStatus.BUSINESS_ERROR,
                'message': '角色被占用,不能删除!!!'
            }
            return CustomerUtils.response_json(response)
